import { Injectable, BadRequestException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { AdminEntity } from "./admin.entity";
import { Repository, getRepository } from "typeorm";
import { MsgService } from "src/msg/msg.service";
import * as argon2 from "argon2";

export interface UserLogin {
  username: string;
  password: string;
}

@Injectable()
export class AdminService {
  constructor(
    @InjectRepository(AdminEntity)
    private readonly adminReponsitory: Repository<AdminEntity>,
    private readonly MSG: MsgService
  ) {}

  async findAll() {
    return await this.adminReponsitory.find();
  }

  async findOne({ username }: { username: string }) {
    const user = await this.adminReponsitory.findOne({ username });

    // console.log(user);

    return user ? {
      code: 200,
      data: user,
    } : {
      code: 404,
      message: '用户不存在',
    };
  }

  async login({ username, password }: UserLogin) {
    const user = await this.adminReponsitory.findOne({ username });

    if (!user) {
      return {
        code: 404,
        message: '用户不存在',
      };
    }

    if (await argon2.verify(user.password, password || '')) {
      return {
        code: 200,
        message: '登陆成功'
      };
    }

    return {
      code: 403,
      message: '账户或者密码错误',
    };
  }

  async edit({ username, password }: UserLogin) {
    const user = await this.adminReponsitory.findOne({ username });

    if (!user) {
      return {
        code: 404,
        message: '用户不存在'
      };
    }

    let update = {...user, password: await argon2.hash( password )};

    return this.adminReponsitory.save(update);
  }

  async create(dto: { username: string; password: string; }) {
    const { username, password } = dto;

    const qb = await getRepository(AdminEntity)
      .createQueryBuilder('user')
      .where('user.username = :username', { username })

    const user = await qb.getOne();

    if (user) {
      this.MSG.fail('用户名不能重复', 400);
    }

    let newUser = new AdminEntity();

    newUser.username = username;
    newUser.password = password;

    const saveUser = await this.adminReponsitory.save(newUser);

    return {
      data: {},
      message: 'success'
    };
  }
}
